package com.zrkizzy.seckill.annotation.validator;

import com.zrkizzy.seckill.annotation.IsMobile;
import com.zrkizzy.seckill.utils.ValidatorUtil;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 校验手机号注解实现类
 *
 * @author zhangrongkang
 * @since 2023/3/21
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    /**
     * 初始默认为非必填项
     */
    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        // 如果当前值是必填项
        if (required) {
            return ValidatorUtil.isMobile(value);
        }
        // 如果此时没有值则直接返回true
        if (!StringUtils.hasLength(value)) {
            return true;
        }
        // 如果此时有值则校验当前值
        return ValidatorUtil.isMobile(value);
    }
}
